package myJs.admin.limitManage

import com.softwaremill.quicklens._
import myJs.Utils
import myJs.api.Api
import myJs.cps._
import myJs.myPkg._
import myJs.myPkg.reactBootstrap.Modal
import myJs.myPkg.reactHookForm._
import myJs.register.Schema
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.web.html._

import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.{Date, JSON}

/**
 * Created by yz on 21/1/2022
 */
@react object ModifyLimitCp {

  case class Props(refreshTableB: () => Future[Unit], show: Boolean = false, showChange: Boolean => Unit,
                   user: UserData, userChange: UserData => Unit)

  val component = FunctionalComponent[Props] { props =>

    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange",
      resolver = yupResolver(ModifyLimitSchema.schema)
    ))

    object FTool {

      def handleClose = () => {
        props.showChange(false)
      }

      def nameChange = (v: String) => {
        val newRow = props.user.modify(_.name).setTo(v)
        props.userChange(newRow)
      }

      def passwordChange = (v: String) => {
        val newMember = props.user.modify(_.password).setTo(v)
        props.userChange(newMember)
      }

      def remainTimesChange = (v: String) => {
        val newX = props.user.modify(_.remainTimes).setTo(v)
        props.userChange(newX)
      }

      def startTimeChange = (v: String) => {
        val newX = props.user.modify(_.startTime).setTo(v)
        props.userChange(newX)
      }

      def endTimeChange = (v: String) => {
        val newX = props.user.modify(_.endTime).setTo(v)
        props.userChange(newX)
      }

      def timeCheck(timeId: String, msg: String) = {
        val startTime = new Date(props.user.startTime.replace("-", "/").replace("-", "/"))
        val endTime = new Date(props.user.endTime.replace("-", "/").replace("-", "/"))
        val startTimeDouble = startTime.getTime()
        val endTimeDouble = endTime.getTime()
        if (!startTimeDouble.isNaN && !endTimeDouble.isNaN &&
          startTimeDouble > endTimeDouble) {
          layer.msg(msg, LayerOptions(icon = 5, time = 1500))
          false
        } else {
          true
        }

      }

      def totalCheck = {
        timeCheck("", "开始日期不能大于截止日期！")
      }

      def update = () => {
        if (totalCheck) {
          val index = layer.alert(Utils.element, Utils.layerOptions)
          Api.admin.addDays(props.user).map { xhr =>
            props.refreshTableB().map { x =>
              layer.close(index)
              props.showChange(false)
              swal(SwalOptions(title = "成功", text = "设置权限成功！", `type` = "success"))
            }
          }
        }
        ()
      }

      def formSubmit = useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
        println(JSON.stringify(data))
        FTool.update()
      })

    }

    Modal(onHide = FTool.handleClose, show = props.show, size = "addDaysModal")(
      Modal.Header(bsPrefix = "modal-header bg-primary", closeButton = true)(
        Modal.Title(
          i(className := "fa fa-edit"),
          span(style := Style(fontWeight = "bold"), id := "lblAddTitle", " 设置权限")
        )
      ),
      form(id := "form", data - "toggle" := "validator", className := "form-horizontal", onSubmit := FTool.formSubmit,
        Modal.Body(
          div(className := "row-fluid",
            InputInlineCp(useForm = useForm, label = "用户名", name = "name", labelWidth = 3, inputWidth = 6,
              value = props.user.name, onChange = FTool.nameChange, readOnly = true
            ),
            InputInlineCp(useForm = useForm, label = "有效次数", name = "remainTimes", labelWidth = 3, inputWidth = 6,
              value = props.user.remainTimes,
              onChange = FTool.remainTimesChange),
            DateTimePickerInlineCp(useForm = useForm, label = "开始日期", name = "startTime", labelWidth = 3, inputWidth = 6,
              value = props.user.startTime,
              onChange = FTool.startTimeChange),
            DateTimePickerInlineCp(useForm = useForm, label = "截止日期", name = "endTime", labelWidth = 3, inputWidth = 6,
              value = props.user.endTime,
              onChange = FTool.endTimeChange),
          )
        ),
        Modal.Footer(bsPrefix = "modal-footer bg-info")(
          button(`type` := "submit", className := "btn blue", "确定"),
          button(`type` := "button", className := "btn green", data - "dismiss" := "modal", "取消",
            onClick := FTool.handleClose),
        )
      )

    )
  }


}
